<template>
  <div class="articleList">
    <van-pull-refresh success-duration="1000" :success-text="tipText" v-model="isLoading" @refresh="onRefresh">
        <!-- v-model="loading"  控制当前是在加载中，如果在加载中是不会下载数据-->
      <!-- :finished="finished"  -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败点击重试"
      @load="onLoad"
    >
      <!-- <van-cell v-for="item in list" :key="item.art_id" :title="item.title" /> -->
    <article-item :row="item" v-for="item in list" :key="item.art_id+''" />
    </van-list>
  </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  components: { ArticleItem },
  props: {
    channelId: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      error: false,
      isLoading: false,
      tipText: ''
    }
  },
  methods: {
    // 1 进入页面，并显示 list 列表组件触发
    // 2 加载的数据没有沾满屏 ，继续加载下一页
    // 3，触底的时候
    async  onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // 1.发送请求获取数据
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          with_top: 1,
          timestamp: this.timestamp
        })
        console.log(res)
        if (Math.random() > 0.5) {
          console.lo(1)
        }
        this.list.push(...res.results)
        this.timestamp = res.pre_timestamp
        this.loading = false
        if (!res.results.length) {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
      // 2 保存数据
      // this.list.push(this.list.length + 1)
      // 3，让当前加载结束
      // 4判断数据是否全部加载
    },
    async onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          with_top: 1,
          timestamp: Date.now()
        })
        if (Math.random() > 0.5) {
          console.lo(1)
        }
        this.list.unshift(...res.results)
        this.isLoading = false
        this.tipText = '刷新成功'
      } catch (err) {
        // console.log(123)
        this.isLoading = false
        this.tipText = '刷新失败'
      }
    }
  },

  created () {

  }

}
</script>

<style scoped lang='less'>
.articleList{
  height: 80vh;
  overflow-y: scroll;
}
</style>
